<template>
    <div id='myApp'>
        <Row style="margin-bottom: 10px;border-bottom: 1px solid #eeeeee;">
            <Col span="5" style="border-bottom:2px solid #2d8cf0 ;padding: 0 0 8px 18px;">
            <span style="color: #2d8cf0;">
                <Icon type="md-add-circle" />&nbsp;&nbsp;
                <span style="color: black;">接口管理&nbsp;&nbsp;>&nbsp;&nbsp;</span>发布API
            </span>
            </Col>
        </Row>
        <Row>
            <Col span="14" offset="2">
            <Form ref="formItems" :rules="ruleValidate" :model="formItems" :label-width="180">
                <FormItem prop="name" label="API名称：">
                    <Input v-model="formItems.name" />
                </FormItem>
                <FormItem prop="des" label="API说明：">
                    <Input type="textarea" v-model="formItems.desc" />
                </FormItem>
                <FormItem prop="url" label="API地址：">
                    <Input v-model="formItems.url" />
                </FormItem>
                <FormItem prop="httpMethod" label="HTTP请求方式：">
                    <RadioGroup v-model="formItems.httpMethod">                        
                        <Radio label="POST">POST</Radio>
                        <Radio label="GET">GET</Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem prop="sqlTemplate" label="SQL任务：">
                    <!-- <Input type="textarea" v-model="code" /> -->
                    <!-- <div style="border: 1px solid #ccc;">
                        <textarea ref="mycode" class="codesql" v-model="code" onChange="changeCode(code)" style="height:200px;width:100%;border:none;"></textarea>
                    </div> -->
                    <div class="editor_form" style="border: 1px solid #ccc;">
                        <codemirror
                          ref="myCm"
                          v-model="formItems.sqlTemplate"
                          :options="cmOptions"
                          class="code">
                        </codemirror>
                    </div>
                    <Button type="text" @click="exeSql" style="float: right; color: #2d8cf0;">执行SQL查询</Button>
                </FormItem>
                <FormItem prop="enabled"" label="状态：">
                    <Checkbox v-model="formItems.enabled">启用</Checkbox>
                </FormItem>
                <FormItem prop="remark" label="备注：">
                    <Input type="textarea" v-model="formItems.remark" />
                </FormItem>
                <FormItem prop="frequency" label="缓存更新频率：">
                    <Input type="number" v-model="formItems.frequency"><span slot="append">分钟</span></Input>
                </FormItem>
                <FormItem>
                    <Button type="primary" @click="saveApi">保存</Button>
                </FormItem>
            </Form>
            </Col>
        </Row>


    </div>
</template>
<style scoped>
.codesql {
font-size: 11pt;
font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif;
}
</style>
<script>
import { mapState, mapActions } from 'vuex'
import zmitiUtil from '../../lib/util'
import { codemirror } from 'vue-codemirror'
import "codemirror/theme/ambiance.css";
import "codemirror/lib/codemirror.css";
import "codemirror/addon/hint/show-hint.css";
require("codemirror/lib/codemirror");
require("codemirror/addon/edit/matchbrackets");
require("codemirror/addon/selection/active-line");
require("codemirror/mode/sql/sql");
require("codemirror/addon/hint/show-hint");
require("codemirror/addon/hint/sql-hint");
    export default {
        computed: mapState({
            Authorization: state => state.Authorization,
            sqlstr:state => state.sqlstr
        }),
        components:{
            codemirror
        },
        data() {
            const validateApiurl = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('请输入API地址'));
                }
                // 异步验证
                setTimeout(() => {
                    var path='apiweb/list';
                    var postData = {
                        pageSize:10,
                        pageNO:1,
                        url:value
                    };
                    zmitiUtil.Ajax(path,postData).then(res => {
                        var data = res.data;
                        
                        if(res.data.total>0){
                            value=res.data.results[0].url;
                            callback(new Error('API地址已存在'));
                        }else{                            
                            callback();
                        }
                        
                    }).catch((error) => {
                        console.log(error,'error');
                    });

                }, 1000);
            };
            return {
                code:'',
                formItems: {
                    name:'',
                    url:'',
                    httpMethod:'POST',
                    enabled:true,
                    sqlTemplate:'',
                    desc:'',
                    frequency:60,
                    parameters:[],
                    remark:''
                },
                ruleValidate: {
                    name: [{
                        required: true,
                        message: "请输入API名称",
                        trigger: "blur"
                    }],
                    url: [{
                        validator: validateApiurl,
                        required: true,
                        trigger: "blur"
                    }],
                    task: [{
                        required: true,
                        message: "请输入SQL任务",
                        trigger: "blur"
                    }]
                },
                editor:'',
                curCode:'',
                cmOptions:{
                    value:'',
                    mode: 'text/x-mariadb',
                    indentWithTabs: false,
                    autoRefresh: true,
                    smartIndent: true,
                    lineNumbers: true,
                    matchBrackets: true,
                    extraKeys: {'Ctrl': 'autocomplete'},//自定义快捷键
                    hintOptions: {//自定义提示选项
                        tables: {
                          users: ['name', 'score', 'birthDate'],
                          countries: ['name', 'population', 'size']
                        }
                    }
                }
            }
        },
        mounted() {
            this.formItems.sqlTemplate=this.sqlstr;
            console.log(this.sqlstr,'store中的sql语句');
        },
        methods: {
            saveApi() {//添加接口            
                var _this = this;                
                var path='apiweb/save';
                //_this.formItems.sqlTemplate=_this.editor.getValue(_this.code);
                let sqlTemplate=_this.formItems.sqlTemplate;
                let isWhere = sqlTemplate.toLowerCase().indexOf('where');
                if(isWhere>0){
                    let sqlwhere = _this.formItems.sqlTemplate.substring(isWhere);                  
                    let sqlarr=sqlwhere.match(/\{(.+?)\}/g);
                    if(sqlarr!=null){
                        //console.log(sqlarr,'sqlarr');
                        let parametersArr=[];
                        sqlarr.map((item,index)=>{                            
                            parametersArr.push(zmitiUtil.getBracketStr(item));
                        })
                        _this.formItems.parameters=JSON.stringify(parametersArr);
                    }
                }                
                var postData = _this.formItems;
                console.log(postData,'postData-保存');             
                this.$refs['formItems'].validate((valid) => {
                    if (valid) {
                        
                        zmitiUtil.Ajax(path,postData).then(res => {
                            var data = res.data;               
                            if (data.code==1) {
                                _this.$Message.success('添加成功!');
                                _this.$router.push({
                                    name:'APIList'
                                })
                            }else{
                                console.log(res.data,'错误');
                                _this.$Message.error(data.result);
                            }
                        }).catch((error) => {
                            console.log(error,'error');
                        });
                    } else {
                        this.$Message.error('请填写完整');
                    }
                })
            },
            exeSql(){//前往执行sql语句页面,并附带sql语句
                var _this = this;
                this.$router.push('/sqlSearch');
                this.$store.state.sqlstr=_this.formItems.sqlTemplate;
            },
        }
    }
</script>